/*INIT*/

//防止重复提交变量
var checkSubmitFlg = true;

function topLayout(){
	if($(".left_490").length>0){
		$("#back").css({display:'block',top:$(".left_490").offset().top,left:$(".left_490").offset().left-60}).click(function(){
			window.location  = $('#resturantUrl').attr('href');
		});
	}else{
		$("#back").css({display:'none'});
	}
}
$(window).resize(function(){
	topLayout();
});
$(document).ready(function() {
	if($('.payType li.active').length==0){
		$('.payType li.online').click();
	}
	topLayout();
	if($("#currentInputAddress").length>0){
		$("#currentInputAddress").focus(function(){
			$('.tips').html("")
		});
	}
	if($("#currentInputTel").length>0){
		$("#currentInputTel").focus(function(){
			$('.tips_phone').html("")
		});
	}
	var count_ = {
			plusMinus:function(){
				$('.plus').click(function(){
					
				});
				$('.minus').click(function(){
					
				});
			},
			getCookie:function(){
				var cookie_ = $.cookie('shoppingCart');
				cookie_ = eval('('+cookie_+')');
				return cookie_;
			},
			refreshCookie:function(args){
				$.cookie('shoppingCart',JSON.stringify(args), { path: '/', expires: 0 });
			}
	};
	count_.plusMinus();
	$('.confirmOrder').click(function(e){
	
		//将按钮隐藏，显示tips，但是此种实现UE效果不好
		$('.confirmOrder').show();
		$('.confirming').hide();

		orderInfo.assembleData();
		
		if(orderInfo.validateData() == false) {
			e.preventDefault();
			return;
		}
		
		if(orderInfo.payType == 'online' && checkBindTelStatus() == false) {
			e.preventDefault();
			return;
		}
		 
		//弹框点击关闭按钮隐藏弹框
		$('#invalidOrder_pop .close').on('click', function(){
			$('#invalidOrder_pop').hide();
		});
		
		var checker = {
				timerClear:null,
				sendcoder:function(args){
						$.ajax({
						url:args.url,
				        cache : false,
				        async : true,
				        type : "POST",
				        //timeout: 30000, //超时时间：30秒
				        data :args.data,
				        dataType:'json',
				        beforeSend:function(xmlHttpRequest){
						},
				        success:function (result){
				        	args.callback(result);
				        },
				        error:function(e){
				        }
				    });
				},
				sender:function(){
					var args_ = {
						url:'/mvc/common/sms/checkcode/sendCheckSMS.do',
						data:{phoneNum:orderInfo.telephone},
						callback:function(data){
							if($('.check_code_btn').hasClass('check_code_btn_active')){
								$('.check_code_btn').removeClass('check_code_btn_active')
							};
							checker.timer();
						}
					};
					$('.check_timer').html('60');
					checker.sendcoder(args_);
				},
				timer:function(){
						var timercheck = $('.check_timer').html();
						if(timercheck!=''){
							checker.timerClear = setInterval(function(){
								var times = parseInt($('.check_timer').html())-1;
								if(times==0){
									times = 60;
									clearInterval(checker.timerClear);
									$('.check_timer').html('');
									$('.check_code_btn').addClass('check_code_btn_active');
									$('.check_code_btn').bind('click',function(){
										checker.sender();
									});
								}else{
									$('.check_code_btn').unbind('click');
									$('.check_timer').html(times)
								}
							 },1000);
						}
						
				},
				checker:function(){
					if($('.check_code').val()!=''){
						var args_ = {
							url:'/mvc/common/sms/checkcode/checkSMS.do',
							data:{checkCode:$('.check_code').val(),phoneNum:orderInfo.telephone},
							callback:function(data){
								if(data.status=='success'){
    								checker.submitOrder();
    								$('.check_code_tip_a').html('');
								}else if((data.status=='error')){
									$('.check_code_tip_a').html("验证码错误，请重新输入");
									return;
								}
							}
						}
						checker.sendcoder(args_);
					}else {
						$('.check_code_tip_a').html('请输入验证码');
					}					
				},
				submitCode:function(){
					$('.check_btn').click(function(){
						checker.checker();
					});
					$('.check_close').click(function(){
						if(checker.timerClear!=null){clearInterval(checker.timerClear);}
						showHeaderShadowHidden();
					});
				},
				pushCookie:function(arg){
					$.cookie('phone_', JSON.stringify(arg.phone), { path: '/', expires: 60*60*12 });
				},
				popCookie:function(){
					var phone_ = $.cookie('phone_');
					if(phone_!=null){
						return eval('('+phone_+')');
					}else{
						return new Array();
					}
				},
				checkElement:function(arr,ele){
					var flag = false;
					for(var i = 0;i<arr.length;i++){
						if(arr[i]==ele){
							flag = true;
							break;
						}
					}
					return flag;
				},
				submitOrder:function(){
					var phone = checker.popCookie();
					if(!checker.checkElement(phone,orderInfo.telephone)){
						phone.push(orderInfo.telephone);
						checker.pushCookie({phone:phone});
					}
					if(checkSubmitFlg){
						checkSubmitFlg = false;
						shoppingCart.phoneNum = orderInfo.telephone;
						shoppingCart.customerId = $('#customerId').val();
						//shoppingCart.refrushCookie();
						//异步提交
						$.ajax({
							url : getRootPath() + '/customerajax/item!submitOrder.action?',
							cache : false, 
							async : true,
							type : "POST",
							timeout: 30000, //超时时间：30秒
							data : {lockToken : $('#lockToken').val(),address : orderInfo.address, contactPhone : orderInfo.telephone,contactShortPhone:orderInfo.shortTelephone,CNote : orderInfo.remarks, payType : orderInfo.payType},
							dataType:'json',
							beforeSend:function(xmlHttpRequest){
								$('.confirmOrder').hide();
								$('.confirming').show();
							},
							success : function (result){
								if(result.submitStatus == 0){

									if(result.payType == 'online') {
										window.location = getRootPath() + "/payinfo/" + result.orderSequence;
									}else {
										var orderId = result.orderId;
										var address = orderInfo.address;
										var phone = orderInfo.telephone;
										var remarks = orderInfo.remarks;
										window.location = getRootPath() + "/mvc/order/successSubmitOrder/" + orderId;
									}
								}else{
									$('#invalidOrder_pop .t2').html(result.submitResult); 
									switch (result.submitStatus) {
										case 1:
											$('#invalidOrder_pop .backBtn').html("返回原餐馆");
											break;
										case 4:
											deleteOrderRelatedCookie();
											$('#invalidOrder_pop .backBtn').html("返回原餐馆");
											break;
										case 2:
										case 3:
										case 5:
										default:
											deleteOrderRelatedCookie();
											$('#invalidOrder_pop .backBtn').addClass("backSup");
											$('#invalidOrder_pop .backBtn').html("重新选美食");
											break;
									};
									invalidOrder();
								}
							},
							error	:	function(e){
								if(e.status >= 400 && e.status < 500) {
									$('#invalidOrder_pop .t2').html("提交订单超时!请返回餐馆页面重新提交订单");  
								}else if(e.status >= 500) {
									$('#invalidOrder_pop .t2').html("服务器忙!请返回餐馆页面重新提交订单");  
								}else{
									$('#invalidOrder_pop .t2').html("网络故障!请检查网络设置并重新提交订单");
								}
								invalidOrder();
							}
						});
					}else{
						$('#invalidOrder_pop .t2').html("请不要重复提交订单!返回餐馆页面重新提交订单");
						invalidOrder();
					}
				}
			};
		var args_ = {
				div_:"<div class='check_ctner'><a class='check_title f-18'>手机验证</a><a class='check_close'>x</a><div class='check_cc'><div class='check_tip f-14 f-tc'><a>您的手机号首次在此电脑下单，请先验证手机号</a></div><p class='check_msg'>验证码已发送至<span>"+orderInfo.telephone+"</span></p><div><input type='text' class='check_code' placeholder='验证码'><span class='check_code_btn mous_pointer' >重新发送<span class='check_timer'>60</span></span></div><div class='check_code_tip'><a class='check_code_tip_a'></a></div><div><input type='button' value='提交验证码' class='check_btn'></div></div></div>",
				callback:function(){
					checker.sender();	
					checker.submitCode();
				}
		};
		var phone_ = checker.popCookie();
		//if((phone_.length==0)||(!checker.checkElement(phone_,orderInfo.telephone))){
		//	showHeaderShadow(args_);
		//}else if(checker.checkElement(phone_,orderInfo.telephone)){
			checker.submitOrder();
		//}
		
	});
	
	shoppingCart.initFromCookie();
	$("#container .backLink, .progress .text .text_2").click(function(){
		  window.location = getRootPath()+"/customer/backToShop!check.action?res="+shoppingCart.supplierId;
	});
});

/**
 * 这个奇葩的function命名,特么当时我是怎么想出来的!!
 */
function checkBindTelStatus() {
	var res = null;
	$.ajax({
		url : getRootPath() + "/mvc/user/bindTelStatus",
		cache : false,
		async : false,
		dataType : 'json',
		success : function(result) {
			if(result.status == 'error') {			
				if(result.msg == 'notLogin') {
					cart.showLoginPromotion();
				} else if(result.msg == 'notBindTel') {
					cart.showBindTelInfo();
				}
				res = false;
			} else {
				res = true;
			}
		},
		
		error : function(e) {
			
			$('#invalidOrder_pop .backBtn').html('返回原餐馆');
			$('#invalidOrder_pop .backBtn').removeClass('notLogin');
			$('#invalidOrder_pop .backBtn').removeClass('notBindTel');
			
			
			if(e.status >= 400 && e.status < 500) {
        		$('#invalidOrder_pop .t2').html("提交订单超时!请返回餐馆页面重新提交订单");  
        	}else if(e.status >= 500) {
        		$('#invalidOrder_pop .t2').html("服务器忙!请返回餐馆页面重新提交订单");  
        	}else{
        		$('#invalidOrder_pop .t2').html("网络故障!请检查网络设置并重新提交订单");
        	}
        	res = false;
		}
	})
	return res;
}


function invalidOrder() {
	var t = $(document).scrollTop()+$(window).height()/2-85;
	$('#invalidOrder_pop .c').css('top', t+'px');
	$('#invalidOrder_pop').show();
	$('#invalidOrder_pop .backBtn').click(function() {
		if ($(this).hasClass("backSup")) {
			window.location = getRootPath();
		}else{
			window.location = getRootPath()+"/customer/backToShop!check.action?res="+shoppingCart.supplierId;
		}
	});	
}

function deleteOrderRelatedCookie(){
	$.cookie('shoppingCart', null, { path: '/', expires: 0 });
}

function ShoppingCart(){
	this.supplierId = null;
	this.customerId = null;
	this.supplierName = null;
	this.phoneNum = null;
	this.deliveryCharge = 0;
	this.deliveryTime = 0;
	this.price = 0;
	this.actualPrice = 0;
	this.productList = null;
	this.num = 0;
	
	this.refrushCartView = function(){
		
		require_template('shoppingCart');
		
		var productListTemplate = $('#template_shoppingCart').html();
		$('#order-ul-list').html(_.template(productListTemplate, {list:this.productList, deliveryCharge: this.deliveryCharge}));
		
		$('#supplierName').html(this.supplierName);
	    $('#totalNum').html(this.num + '');
	    $('#totalPrice').html(this.price + '');
	    $('#totalPoint').html(accMul(this.price,10) + '分');
	    $('#expressAll').html(this.deliveryCharge + '');
	    $('#payAll').html(this.actualPrice + '');
	};
	
	this.refrushCookie = function(){
		$.cookie('shoppingCart', JSON.stringify(shoppingCart), { path: '/', expires: 60*60*12 });
	};
	
	this.initFromCookie = function(){
		var str =  $.cookie('shoppingCart');
		return;
		$.ajax({
			url:"mvc/shoppingCart",
			type:"get",
			data:'json',
			success:function(data){
				console.log(data);
			},error:function(data){
				console.log(data);
			}
			
		})
		if(str!=null && $.trim(str) != ''){
			var obj = eval('(' + str + ')');
			this.customerId = obj.customerId;
			this.phoneNum = obj.phoneNum;
			this.price = obj.price;
			this.productList = obj.productList;
			this.supplierId = obj.supplierId;
			this.num = obj.num;
			this.supplierName = obj.supplierName;
			this.deliveryCharge = obj.deliveryCharge;
			this.actualPrice = obj.price;
		}
		this.refrushCartView();
	};	
}

function Product(){
	this.name = null;
	this.price = 0;
	this.isCombine = false;
	this.num = 0;
	this.productId = null;
	this.combineList = null;
}

var shoppingCart = new ShoppingCart();

/**
 *  填写的订单信息
 */
function OrderInfo() {
	this.address = null;
	this.telephone = null;
	this.shortTelephone = null;
	this.remarks = null;
	this.payType = null;
}

OrderInfo.prototype.assembleData = function() {
	
	if($.trim($('#addressLayer ul.address-list-ul').html()) != '') {
		this.address = $.trim($('.order-info .list-unstyled span.room-res-address').text());
		this.telephone = $.trim($('.order-info .list-unstyled span.room-res-phone').eq(0).text());
		this.shortTelephone = $.trim($('.order-info .list-unstyled span.room-res-phone').eq(1).text());
	} else {
		this.address = $.trim($('.order-info input[name=address]').val());
		this.telephone = $.trim($('.order-info input[name=tel]').val());
		this.shortTelephone = $.trim($('.order-info input[name=shortTel]').val());
	}
	
	this.remarks = $('textarea[name=remarks]').val();
	
	//备注里加入送达时间
	if($('select.sendTime').val() != '立即送出') {
		this.remarks =   '[' + $('select.sendTime').val() + ' 送达] ' +  this.remarks;
	}
	
	if($('.payType .active').hasClass('online')) {
		this.payType = "online";
	} else {
		this.payType = "offline";
	}
}

OrderInfo.prototype.validateData = function() {
	if(this.address.length>255 || this.address.length<1){
		$('.tips').html("请认真填写地址！");
		return false;
	}
	$('.tips').html("");
	if((!/^(13[0-9]|147|15[0|1|2|3|5|6|7|8|9]|18[0-9])\d{8}$/.test(this.telephone))){
		$('.tips_phone').html("请填写正确的电话号码!").addClass('tips_phonemsg');
		return false;
	}$('.tips_phone').html("").removeClass('tips_phonemsg');
	if(this.remarks.length>35){ 
		alert("备注限定在24个字以内！");
		return false;
	}
	return true;
}

var orderInfo = new OrderInfo();



/**
 * 某些部分的refactory
 */

	
var cart = {};

var showBindTelPromotion = function(){
	$('.promption-info').html('<p>在线支付请先 <a style="color:#34aadc;" href=' +getRootPath() + '/customer/securityCenter/security.jsp'  + '>绑定手机</a></p>');
	$('.promption-info').show();
};
cart.showBindTelInfo = showBindTelPromotion;


var showLoginPromotion = function() {
	$('.promption-info').html('<p>在线支付请先 <a  style="color:#34aadc;" href=' +getRootPath() + '/customer/login!login.action?backUrl=%2Fmvc%2FshoppingCart' + '>登录</a></p>');
	$('.promption-info').show();
};
cart.showLoginPromotion = showLoginPromotion;


	

